package com.newsmanagement.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import net.sf.json.JSONObject;

/**
 * 已经测试通过
 * @author xbr
 *
 * 此图片发送后变为.bin文件，请查找问题（原此class已测试通过，重新导包后出现此问题）
 */
public class EmailSimple {

	public static void main(String[] args) throws AddressException {
		
		Properties proper = new Properties(); 
		
		//邮件传输协议
		proper.setProperty("mail.transport.protocol", "smtp");
		//邮件服务器
		proper.setProperty("mail.smtp.host", "smtp.163.com");
		//接口
		proper.setProperty("mail.smtp.port", "25");
		//是否身份验证
		proper.setProperty("mail.smtp.auth", "true");
		//是否使用debug模式
		proper.setProperty("mail.debug", "true");
		
		//收件人
		List<String> addressList = new ArrayList<String>();
		addressList.add("985174442@qq.com");
		addressList.add("125491472@163.com");
		//addressList.add("710349447@qq.com");
		
		//附件路径
		List<String> attachPathList = new ArrayList<String>();
		attachPathList.add("E:\\测试\\my.txt");
		attachPathList.add("E:\\测试\\current.txt");
		
		//图片路径
		List<String> imgPathList = new ArrayList<String>();
		imgPathList.add("E:\\测试\\imgs\\banner_01.png");
		imgPathList.add("E:\\测试\\imgs\\banner_02.png");
		
		String content =  "<span style='color:red'>这是我自己用java mail发送的邮件哦！</span><img src='cid:banner_01'/><img src='cid:banner_02'/>" ; 
		JSONObject json = new JSONObject();
		//发件人
		json.put("fromMail", "xuhongliu0125@163.com");
		//发件人密码
		json.put("fromMailPassword", "xuhongliu0125");
		//收件人
		json.put("toMail", addressList);
		//文件编码格式
		json.put("charset", "utf-8");
		//标题
		json.put("subject", "邮件标题");
		//邮件正文
		json.put("content", content);
		//邮件正文格式
		json.put("contentType", "text/html;charset=UTF-8");
		//附件
		json.put("attachList", attachPathList);
		//正文图片
		json.put("imgList", imgPathList);
		
		sendMail(proper, json);
		
	}
	
	/**
	 * 邮件发送
	 * @param proper 邮件服务配置信息
	 * @param json 邮件信息prize信息
	 * @return Map<String ,Object>
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	public static Map<String ,Object> sendMail(Properties proper ,final JSONObject json){
		Map<String ,Object> map = new HashMap<String ,Object>();
		map.put("check", "false");
		map.put("message", "");
		map.put("object", null);
		
		String charset = json.getString("charset");
		try {
			//邮件发送
			//1、信息对象获取
			Session session = Session.getInstance(proper);
			//同方法一一起使用
			//MimeMessage mimeMessage = new MimeMessage(session);
			//同方法二一起使用
			MimeMessage mimeMessage = new MimeMessage(
						Session.getInstance(proper, new Authenticator(){
							@Override
							public PasswordAuthentication getPasswordAuthentication() {  
		                        return new PasswordAuthentication(
										//设置发送帐号密码
		                        		json.getString("fromMail"), json.getString("fromMailPassword"));  
		                    } 
						})
					);
			
			//2、文件收发件账户信息设置
			//发件人
			mimeMessage.setFrom(new InternetAddress(json.getString("fromMail")));
			
			//收件人
			List<String> addressList = (List<String>) json.get("toMail");
			//收件人地址
			Address[] toMail = new InternetAddress[addressList.size()];
			
			int j = 0;
			if(null != addressList){
				for (int i = 0; i < addressList.size(); i++) {
					if(null != addressList.get(i) && !"".equals(addressList.get(i).trim())){
						toMail[j] = new InternetAddress(addressList.get(i));
						j ++;
					}
				}
			}else{
				map.put("message", "收件人未设置！");
				return map;
			}
//			mimeMessage.setRecipients(RecipientType.TO, new InternetAddress().parse("985174442@qq.com"));
			mimeMessage.setRecipients(RecipientType.TO, toMail);
			
			//发件时间
			mimeMessage.setSentDate(new Date());
			
			//3、邮件内容
			//标题
			mimeMessage.setSubject(json.getString("subject"), charset);
			
			//正文
			//mimeMessage.setContent(json.getString("content"), json.getString("contentType"));
			//整个邮件对象获取:mixed表示有附件
			MimeMultipart mimeMultipart = new MimeMultipart("mixed");
			mimeMessage.setContent(mimeMultipart);
			
			//附件
			if(null != json.get("attachList")){
				//单个附件路径
				String attachPath = "";
				List<String> attachList = (List<String>) json.get("attachList");
				for (int i = 0; i < attachList.size(); i++) {
					attachPath = attachList.get(i);
					if(null != attachPath && !"".equals(attachPath.trim())){
						File file = new File(attachPath);
						
						//附件
						MimeBodyPart attach = new MimeBodyPart();
						attach.setFileName(file.getName());
						attach.setDataHandler(new DataHandler(new FileDataSource(file)));
						mimeMultipart.addBodyPart(attach);
					}
				}
			}
			
			//正文部分获取
			MimeBodyPart bodyPart = new MimeBodyPart();
			mimeMultipart.addBodyPart(bodyPart);
			
			// 邮件正文(内嵌图片+html文本)
			//邮件正文也是一个组合体,需要指明组合关系
	        MimeMultipart body = new MimeMultipart("related");
	        bodyPart.setContent(body); 
	       
	        //body.addBodyPart(MimeBodyPart图片);
	        //body.addBodyPart(MimeBodyPart正文);
	         
	        //图片
			if(null != json.get("imgList")){
				//单个图片路径
				String imgPath = "";
				List<String> imgList = (List<String>) json.get("imgList");
				for (int i = 0; i < imgList.size(); i++) {
					imgPath = imgList.get(i);
					if(null != imgPath && !"".equals(imgPath.trim())){
						File file =  new File(imgPath);
						
						//图片
						MimeBodyPart imgPart = new MimeBodyPart();
				        //正文图片 
				        DataHandler dh = new DataHandler(new FileDataSource(file)); 
				        imgPart.setDataHandler(dh);
						imgPart.setContentID(file.getName());
				        body.addBodyPart(imgPart); 
					}
				}
			}

			//正文html
	        MimeBodyPart htmlPart = new MimeBodyPart(); 
	       
	        body.addBodyPart(htmlPart); 
	        //html邮件内容
	        MimeMultipart htmlMultipart = new MimeMultipart("alternative");  
	        htmlPart.setContent(htmlMultipart); 
	        MimeBodyPart htmlContent = new MimeBodyPart(); 
	        htmlContent.setContent(json.getString("content"),json.getString("contentType")); 
	        htmlMultipart.addBodyPart(htmlContent); 
			
			//4、邮件发送
	        /*
	        //方法1
			Transport transport = session.getTransport();
			transport.connect(
					proper.getProperty("mail.smtp.host"), 
					Integer.valueOf(proper.getProperty("mail.smtp.port")), 
					json.getString("fromMail"), 
					json.getString("fromMailPassword")
					);
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); 
	        // 关闭连接 
	        transport.close(); 
	        */
			//方法2
			Transport.send(mimeMessage);
			
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}
	}

}
